package myJs.map

import myJs.Implicits._
import myJs.Utils._
import myJs.cps.MyTabCp
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.raw.HTMLFormElement
import scalatags.Text.all
import scalatags.Text.all._
import slinky.web.ReactDOM

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 16/9/2021
 */
@JSExportTopLevel("GeneticMap")
object GeneticMap {

  val tableId = "table"
  var tableRsMap: SeqMap[String, JDJAn] = SeqMap[String, JDJAn]()

  @JSExport("init")
  def init = {
    refreshMaps
    refreshTabsComponents
    registerEvent
  }

  def refreshTabsComponents = {
    ReactDOM.render(MyTabCp(), document.querySelector("#mapsTab"))
  }

  def refreshTableRsMap(indexs: List[String]) = {
    val index = layer.load(1, Tool.layerOptions.copy(shade=List("0.1", "#fff")))
    val fs = indexs.map { index =>
      val url = g.jsRoutes.controllers.ToolController.getFileData().url.toString
      Ajax.get(url = s"${url}?fileName=map/map_${index}.txt").map { xhr =>
        Map(index -> xhr.responseText.toJDJAn)
      }
    }
    Future.sequence(fs).map { maps =>
      layer.close(index)
      tableRsMap = maps.foldLeft(tableRsMap)(_ ++ _)
    }
  }

  def refreshMaps = {
    val url = g.jsRoutes.controllers.ToolController.getFileData().url.toString
    Ajax.get(url = s"${url}?fileName=map/key_to_maps.txt").map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.map { columnName =>
        val fmt = columnName
        ColumnOptions.field(columnName).title(columnName).sortable(true)
      }
      val options = TableOptions.data(rs("array")).columns(columns).search(false).pagination(false)
      $(s"#maps #${tableId}").bootstrapTable(options)
    }
  }

  def rowStyleF: js.Function = (row: JDJAn, index: Int) => {
    if (index == 15) {
      js.Dictionary("css" -> js.Dictionary(
        "font-weight" -> "bold"
      ))
    } else {
      js.Dictionary()
    }
  }

  def initSummaryTables(indexs: List[String]) = {
    indexs.foreach { index =>
      val url = g.jsRoutes.controllers.ToolController.getFileData().url.toString
      Ajax.get(url = s"${url}?fileName=map/map_${index}_summary.txt").map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val map = rs("map").toJDS.toSeqMap
        val columnNames = map.keyList
        val columns = columnNames.map { columnName =>
          val title = map.getOrElse(columnName, columnName)
          val fmt = columnName
          ColumnOptions.field(columnName).title(title).sortable(true)
        }
        val options = TableOptions.data(rs("array")).columns(columns.toJSArray).search(false).pagination(false).rowStyle(rowStyleF)
        $(s"#map${index} #summaryTable").bootstrapTable("destroy").bootstrapTable(options)
      }
    }
  }

  def initTables(indexs: List[String], lg: String) = {
    refreshTableRsMap(indexs).map { x =>
      indexs.foreach { index =>
        val rs = tableRsMap(index)
        val map = rs("map").toJDS.toSeqMap
        val columnNames = map.keyList
        val columns = columnNames.map { columnName =>
          val title = map.getOrElse(columnName, columnName)
          val fmt = columnName
          ColumnOptions.field(columnName).title(title).sortable(true)
        }
        val filterArray = rs("array").toJArJDJAn.filter { dict =>
          dict.myGet("c0") == lg
        }
        val options = TableOptions.data(filterArray).columns(columns.toJSArray).search(false).pagination(true)
        $(s"#map${index} #${tableId}").bootstrapTable("destroy").bootstrapTable(options)
      }
    }
  }

  def refreshTable(index: String, lg: String) = {
    val tableJq = $(s"#map${index} #${tableId}")
    val f = if (tableRsMap.isDefinedAt(index)) {
      Future {}
    } else {
      refreshTableRsMap(List(index))
    }
    f.map { x =>
      val rs = tableRsMap(index)
      val filterArray = rs("array").toJArJDJAn.filter { dict =>
        dict.myGet("c0") == lg
      }
      tableJq.bootstrapTable("load", filterArray)
    }
  }

  def registerEvent = {
  }

}
